package org.easy.file.monitor;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 文件监控
 * @Author: wxl
 * @CreateTime: 2022/12/27 11:27
 */
public class FileMonitor {

    private File file;

    private FileListener listener;

    private IOFileFilter ioFileFilter;

    private FileAlterationMonitor fileAlterationMonitor;

    public FileMonitor (File file) {
        this(file, new ArrayList<>());
    }

    public FileMonitor (File file,List<String> suffixList) {
        this.file = file;
        this.listener = new FileListener();
        this.initIoFileFilter(suffixList);
        this.monitor();
    }

    public void monitor () {
        long interval = TimeUnit.SECONDS.toMillis(1);
        FileAlterationObserver observer = new FileAlterationObserver(getFile(), getIoFileFilter());
        observer.addListener(getListener());
        this.fileAlterationMonitor = new FileAlterationMonitor(interval,observer);
    }

    private void initIoFileFilter(List<String> suffixList) {
        IOFileFilter directories = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), HiddenFileFilter.VISIBLE);
        IOFileFilter[] ioFileFilters;
        if (suffixList.isEmpty()) {
            ioFileFilters = new IOFileFilter[1];
        } else {
            ioFileFilters = new IOFileFilter[suffixList.size() + 1];
            for (int i = 0;i < suffixList.size();i++) {
                int n = i + 1;
                ioFileFilters[n] = FileFilterUtils.suffixFileFilter(suffixList.get(i));
            }
        }
        ioFileFilters[0] = FileFilterUtils.fileFileFilter();
        IOFileFilter fileFilter = FileFilterUtils.and(ioFileFilters);
        IOFileFilter filter = FileFilterUtils.or(directories, fileFilter);
        setIoFileFilter(filter);
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public FileListener getListener() {
        return listener;
    }

    public void setListener(FileListener listener) {
        this.listener = listener;
    }

    public IOFileFilter getIoFileFilter() {
        return ioFileFilter;
    }

    public void setIoFileFilter(IOFileFilter ioFileFilter) {
        this.ioFileFilter = ioFileFilter;
    }

    public FileAlterationMonitor getFileAlterationMonitor() {
        return fileAlterationMonitor;
    }

    public void setFileAlterationMonitor(FileAlterationMonitor fileAlterationMonitor) {
        this.fileAlterationMonitor = fileAlterationMonitor;
    }
}
